<template>
  <div class="coupon-create-page">
    <h2>{{ isEdit ? '编辑优惠券' : '创建优惠券' }}</h2>
    
    <el-card class="form-card">
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="top"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>

        <el-form-item label="优惠券类型" prop="type">
          <el-select 
            v-model="form.type" 
            placeholder="请选择优惠券类型"
            @change="handleTypeChange"
          >
            <el-option
              v-for="item in couponTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 通用优惠券设置 -->
        <el-form-item label="优惠券面值" prop="value" v-if="showValueField">
          <el-input-number 
            v-model="form.value" 
            :min="0" 
            :precision="2" 
            :step="1"
          />
          <span class="unit">元</span>
        </el-form-item>

        <el-form-item label="使用门槛" prop="threshold" v-if="showThresholdField">
          <el-input-number 
            v-model="form.threshold" 
            :min="0" 
            :precision="2" 
            :step="1"
          />
          <span class="unit">元</span>
          <div class="tip">满{{ form.threshold }}元可用</div>
        </el-form-item>

        <!-- 有效期设置 -->
        <el-form-item label="有效期" required>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">至</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="发放总量" prop="total">
          <el-input-number v-model="form.total" :min="1" />
          <span class="unit">张</span>
        </el-form-item>

        <el-form-item label="每人限领" prop="limit">
          <el-input-number v-model="form.limit" :min="1" />
          <span class="unit">张</span>
        </el-form-item>

        <el-form-item label="优惠券说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入优惠券使用说明"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { COUPON_TYPES, createCoupon, updateCoupon, getCouponDetail } from '@/api/coupon'

const route = useRoute()
const router = useRouter()

const isEdit = computed(() => route.path.includes('/edit'))

// 优惠券类型选项
const couponTypes = [
  { value: COUPON_TYPES.NEW_USER, label: '新人券' },
  { value: COUPON_TYPES.FULL_REDUCTION, label: '满减券' },
  { value: COUPON_TYPES.DIRECT_REDUCTION, label: '立减券' },
  { value: COUPON_TYPES.PRODUCT, label: '商品优惠券' },
  { value: COUPON_TYPES.SHOP, label: '店铺优惠券' },
  { value: COUPON_TYPES.REPURCHASE, label: '复购券' },
  { value: COUPON_TYPES.FANS, label: '涨粉券' }
]

// 表单引用
const formRef = ref(null)

// 表单数据
const form = ref({
  name: '',
  type: COUPON_TYPES.DIRECT_REDUCTION,
  value: 10,
  threshold: 100,
  startTime: '',
  endTime: '',
  total: 100,
  limit: 1,
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入优惠券面值', trigger: 'blur' }
  ],
  threshold: [
    { required: true, message: '请输入使用门槛', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  total: [
    { required: true, message: '请输入发放总量', trigger: 'blur' }
  ],
  limit: [
    { required: true, message: '请输入每人限领数量', trigger: 'blur' }
  ]
}

// 计算属性
const showValueField = computed(() => {
  return [
    COUPON_TYPES.DIRECT_REDUCTION,
    COUPON_TYPES.FULL_REDUCTION,
    COUPON_TYPES.NEW_USER
  ].includes(form.value.type)
})

const showThresholdField = computed(() => {
  return form.value.type === COUPON_TYPES.FULL_REDUCTION
})

// 方法
const handleTypeChange = (type) => {
  // 根据类型重置相关字段
  if (type === COUPON_TYPES.FULL_REDUCTION) {
    form.value.value = 10
    form.value.threshold = 100
  } else if (type === COUPON_TYPES.DIRECT_REDUCTION) {
    form.value.value = 5
    form.value.threshold = 0
  }
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await updateCoupon(route.params.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createCoupon(form.value)
      ElMessage.success('创建成功')
    }
    
    router.push('/coupon')
  } catch (error) {
    console.error('提交失败:', error)
  }
}

const resetForm = () => {
  formRef.value.resetFields()
}

// 初始化编辑数据
const initEditData = async () => {
  if (!isEdit.value) return
  
  try {
    const { data } = await getCouponDetail(route.params.id)
    form.value = data
  } catch (error) {
    console.error('获取优惠券详情失败:', error)
    router.push('/coupon')
  }
}

onMounted(() => {
  initEditData()
})
</script>

<style scoped>
.coupon-create-page {
  background: #fff;
  border-radius: 12px;
  padding: 32px 40px;
  min-height: 400px;
  box-shadow: 0 2px 8px #f0f1f2;
}

.form-card {
  margin-top: 20px;
  border-radius: 10px;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.text-center {
  text-align: center;
}
</style>